import os

from PyQt4.QtCore import *
from PyQt4.QtGui import *

##
# A QLineEdit along with a QPushButton to select a file
# emits fileSelected() signal
#
class FileSelector(QWidget):

	def __init__(self, filename=""):
		QWidget.__init__(self)
		self.use_relative_path = True

		layout = QHBoxLayout()
		self.setLayout(layout)
		layout.setSpacing(0)
		layout.setMargin(0)

		self.line = QLineEdit()
		self.line.setText(filename)
		self.line.setReadOnly(True)
		self.line.setFixedWidth(200)
		layout.addWidget(self.line)

		but_browse = QPushButton("Browse...")
		self.connect(but_browse, SIGNAL("clicked()"), self.onSelect)
		layout.addWidget(but_browse)


	def setRelative(self, relative):
		self.use_relative_path = relative


	def onSelect(self):
		# QString to str
		filename = str(QFileDialog.getOpenFileName(self, "Select",
			os.path.dirname(self.getFilename()), "All (*);;"))

		if filename != "":
			# absolute -> relative
			if self.use_relative_path:
				filename = os.path.relpath(filename, os.getcwd())
			self.line.setText(filename)
			self.emit(SIGNAL("fileSelected()"))


	def setFilename(self, filename):
		self.line.setText(filename.strip())


	def getFilename(self):
		return str(self.line.text()).strip()
